// pages/store/store.js
import utils from '../../../utils/utils'
import {
  formatTimeDate,
  throttle,
  debounce
} from '../../../utils/vutils'
import User from '../../../utils/user'
import {
  StoreHttp
} from '../../../api/store'
import {
  EvaluationHttp
} from '../../../api/evaluation'
import {
  storeInfoMap,
  storeGoodsListMap,
  cartListMap,
  cartDiscountsMap,
  cartRecommendGoodMap
} from '../../../utils/dataMap.js'
import {
  TABS_LIST
} from './config'

const storeModel = new StoreHttp()
const evaluationModel = new EvaluationHttp()
const app = getApp();

Page({

  isInitPage: false,

  /**
   * 页面的初始数据
   */
  data: {
    tabList: TABS_LIST, // tab list
    tabActive: 'categroy', // tab
    twoTabList: [], //二级分类
    storeId: '', // 店铺 - 店铺ID
    curTwoIndex: -1,
    curTwoCategroyId: -1,
    storeInfo: {
      serviceCenterId: 0
    }, // 店铺信息
    toPageCategroyId: '', //进入时的类型id
    goodsCategroy: [], // 商品分类
    goodsCategroyId: '', // 商品分类Id
    isSeckillCategroy: false, // 是否为秒杀分类
    isStoreOpen: true, // 店铺 - 店铺是否营业
    storeSidebarIndex: 0, // 店铺 - 店铺是否营业
    isSwitchNextCategroy: false, // 是否切换到下一分类
    longitude: 0, // 店铺 - 当前用户所处位置经度 - 用于计算距离店铺的距离
    latitude: 0, // 店铺 - 当前用户所处位置维度 - 用于计算距离店铺的距离

    // goodsSpecsInfo: {}, // 购物车 - 添加到购物车 - 商品信息
    // goodsSpecsList: {}, // 购物车 - 添加到购物车 - 商品规格列表
    cartDiscountsInfo: {}, // 购物车 - 购物车计算优惠信息
    cartList: [], // 购物车 - 购物车列表
    needGoodsList: [], // 购物车 - 配套商品列表
    isClearingBtnClick: false, // 购物车 - 推荐商品 - 结算按钮是否点击
    isShowCartAlertParent: true, // 购物车 - 推荐商品 - 控制是否显示购车提示（控制购物车提示显示 - 父级）
    isShowCartAlert: false, // 购物车 - 推荐商品 - 是否显示购物车提示（控制购物车提示显示 - 子级）
    // isShowCartList: false, // 购物车 - 购物车列表 - 是否显示购物车列表

    evaluationType: 0, // 评价 - 评论类型：0:全部，1:有图
    evaluationTag: 1, // 评价 - 评论标签：1:全部，2:好评, 3:差评,其他的根据返回的storeScores中有的类型传type值。默认1
    evaluationScrollViewTop: 0, // 评价 - scrollView组件 - 设置竖向滚动条位置

    goodsListScrollViewTop: 0, // scrollView组件 - 设置竖向滚动条位置
    scrollViewHeight: 0, // scrollView组件 - 设置滚动组件高度

    isFirstGoodsRequest: true, // 是否为第一次请求 - 用于店铺分享（店铺分享合成第一个商品图）
    isShowGoodsSkuPopup: false, // 商品 - 是否显示选择商品规格
    isLoading: false, // 商品 - 是否正在请求数据
    isNotMore: false, // 商品 - 是否没有更多数据了

    initUser: true,
    openLogin: false,
  },

  async initPage(options) {
    let self = this;
    const {
      id,
      sid,
      categroyId
    } = options;
    this.setData({
      storeId: id,
      'storeInfo.serviceCenterId': sid,
      toPageCategroyId: categroyId
    });
    this.initScrollViewHeight();
    this.httpGetGoodsCategory() // 请求店铺分类
    // this.httpGetStoreEvaluation() // 获取店铺评价
    // await this.httpWxGetLocation().catch(err => Promise.resolve())
    await this.httpGetStoreInfo(id)
    if (this.isInitPage && this.data.userInfo && this.data.userInfo.uid) {
      this.httpGetCartList() // 请求店铺购物车
    }
    if (options.hasOwnProperty('ekey')) {
      utils.UserUv(options.ekey);
      User.UvTrackPut(options.ekey);
    }
    this.isInitPage = true
  },

  // 初始化商品分类列表容器高度，用于解决 ios 10.2.1 scroll-view滑动问题
  initScrollViewHeight() {
    let self = this
    var query = wx.createSelectorQuery()
    query.select('.store-classify')
      .boundingClientRect(function (rect) {
        console.log('store-classify rect', rect)
        self.setData({
          scrollViewHeight: rect.height
        })
      }).exec()
  },

  // tab选择
  onTabsItem(event) {
    const {
      type
    } = event.currentTarget.dataset;
    if (type === this.data.tabActive) {
      return
    }
    this.setData({
      tabActive: type
    })
  },

  // 店铺分类侧边栏 item - click
  onClickSidebarItem(event) {
    console.log('event', event)
    const {
      id,
      type,
      index
    } = event.currentTarget.dataset
    this.onSelectSidebarItem(id, type, index)
  },

  // 选择店铺分类侧边栏
  onSelectSidebarItem(id, type, index) {
    // console.log('event', event)
    // const { id, type, index } = event.currentTarget.dataset
    const {
      tabList
    } = this.data
    if (id !== this.data.goodsCategroyId) {
      tabList['categroy'].page = 1
      this.setData({
        tabList: tabList,
        goodsCategroyId: id,
        storeSidebarIndex: index,
        isNotMore: false,
        isSwitchNextCategroy: false
      })
      this.setData({
        isSeckillCategroy: type === 2, // 1:普通类目布局，2:秒杀商品布局
      })
      this.httpGetTwoGoodsCategory()
    }
  },

  scrollGoodsListToTop() {
    this.setData({
      goodsListScrollViewTop: 0
    })
  },

  // 购物栏 - 结算
  onClearingCart() {
    const {
      cartList,
      storeId,
      needGoodsList,
      isClearingBtnClick
    } = this.data;
    let serviceCenterId = this.data.storeInfo.serviceCenterId;
    const navToClearing = function () {
      let cartListArr = cartList
        // .filter(item => item.stockStatus === 1 || item.stockStatus === 2)
        .map((item) => {
          return {
            cart_id: item.cartId,
            sku_id: item.goodsSkuId,
            spu_id: item.goodsSpuId,
            amount: item.currentNum,
          }
        });
      wx.navigateTo({
        url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}`
      })
    };
    if (cartList.length === 0) return
    if (needGoodsList.length !== 0) {
      if (isClearingBtnClick) {
        navToClearing()
      } else {
        this.setData({
          isShowCartAlert: true,
          isClearingBtnClick: true
        })
      }
    } else {
      navToClearing()
    }
  },

  // 购物栏提示 - 取消
  onCartAlertCancel() {
    this.setData({
      isShowCartAlertParent: false
    })
  },

  // 购物栏提示 - 确定
  onCartAlertConfirm() {
    const {
      needGoodsList,
      storeId
    } = this.data
    let addCartGoodsInfo = needGoodsList.map(item => {
      return {
        goodsThumbnailUrl: item.goodsImg,
        goodsTitle: item.goodsName,
        skuId: item.goodsSkuId,
        spuId: item.goodsSpuId,
        skuAmount: 1
      }
    })
    let addCartInfo = {
      goods: addCartGoodsInfo,
      storeId: this.data.storeId,
      userId: this.data.userInfo && this.data.userInfo.uid
    }
    this.httpAddCartGoods(addCartInfo).then(() => {
      this.setData({
        needGoodsList: [],
        isShowCartAlert: false
      })
    })
  },

  // 分类商品，上拉加载
  onScrollToLower: throttle(function () {
    console.log('onScrollToLower')
    const {
      tabList,
      tabActive,
      storeSidebarIndex
    } = this.data
    if (!tabList[tabActive].list) return
    const listLen = tabList[tabActive].list.length
    const listTotalNum = tabList[tabActive].totalNum
    // console.log('tabList[tabActive]', tabList[tabActive])
    if (listLen < listTotalNum) {
      tabList[tabActive].page++
      this.setData({
        tabList: tabList,
        isNotMore: false,
      })
      switch (tabActive) {
        case 'categroy':
          this.httpGetGoodsList()
          break;
        case 'evaluation':
          this.httpGetStoreEvaluation()
          break;
        default:
          break;
      }
    } else {
      // if (this.data.isSwitchNextCategroy && tabActive === 'categroy') {
      //   let categroyList = tabList['categroy'].categroyList
      //   let index = storeSidebarIndex + 1 >= categroyList.length ? storeSidebarIndex : storeSidebarIndex + 1
      //   if (index !== storeSidebarIndex) {
      //     let categroyId = categroyList[index].id
      //     let categroyType = categroyList[index].type
      //     // this.setData({
      //     //   storeSidebarIndex: index
      //     // })
      //     this.onSelectSidebarItem(categroyId, categroyType, index)
      //   }
      // } else {
      //   this.setData({
      //     isSwitchNextCategroy: true
      //   })
      // }
      this.setData({
        isNotMore: true
      })
    }
  }, 500, {
    immediate: true
  }),

  //打开搜索页面
  onSearch() {
    wx.navigateTo({
      url: `/pages/store/storeSearch/storeSearch?storeId=${this.data.storeId}&serviceId=${this.data.storeInfo.store_service_id}`,
    })
  },

  // 拨打电话
  onMakePhoneCall() {
    wx.makePhoneCall({
      phoneNumber: this.data.storeInfo.storePhone
    })
  },

  // 评论过滤
  onEvaluationFilter(event) {
    const {
      type,
      tag
    } = event.detail
    const {
      tabList
    } = this.data
    tabList['evaluation'].page = 1
    this.setData({
      tabList: tabList,
      evaluationType: type,
      evaluationTag: tag
    })
    this.httpGetStoreEvaluation()
  },

  // 添加到购物车 - 单规格商品
  onAddCart(event) {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      this.setData({
        openLogin: true,
        initUser: false
      })
      return
    }
    const {
      storeInfo
    } = this.data
    const {
      goods,
      pos
    } = event.detail
    if (storeInfo.cooperationType === 1) {
      // 自营商品 - 加入购物车
      this.selfGoodsAddCart(goods, pos)
    } else {
      // 1688 - 立即购买
      this.otherGoodsAddCart(goods)
    }
  },

  // 自营单规格商品 - 加入购物车
  selfGoodsAddCart(goods, pos) {
    app.event.emit('addCartAnimation', pos)
    let addCartInfo = {
      goods: [{
        goodsThumbnailUrl: goods.goodsThumbnailImg,
        goodsTitle: goods.goodsName,
        skuId: goods.singleSku.goods_sku_id,
        spuId: goods.goodsId,
        skuAmount: 1,
      }],
      storeId: goods.storeId,
      userId: this.data.userInfo.uid
    }
    this.httpAddCartGoods(addCartInfo);
  },

  // 1688 -立即购买
  otherGoodsAddCart(goods) {
    const {
      storeId,
      serviceCenterId
    } = this.data.storeInfo
    let cartListArr = [{
      // cart_id: item.cartId,
      sku_id: goods.singleSku.goods_sku_id,
      spu_id: goods.goodsId,
      amount: 1,
    }]
    wx.navigateTo({
      url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}&type=3`
    })
  },

  // 添加到购物车 - 选择商品规格 - 多规格商品
  onSelectSku(event) {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      this.setData({
        openLogin: true,
        initUser: false
      })
      return
    }
    const {
      goods
    } = event.detail
    this.setData({
      multiSkuGoodsInfo: goods,
      isShowGoodsSkuPopup: true
    })
  },

  // 选择商品规格 - 多规格商品 - 加入购物车
  onSkuAddCart(event) {
    const {
      storeInfo
    } = this.data
    if (storeInfo.cooperationType === 1) {
      // 自营商品 - 加入购物车
      let addCartInfo = {
        goods: [event.detail],
        storeId: this.data.storeId,
        userId: this.data.userInfo.uid
      }
      this.httpAddCartGoods(addCartInfo).then((res) => {
        this.setData({
          isShowGoodsSkuPopup: false
        })
      });
    } else {
      // 1688 - 立即购买
      const {
        storeId,
        serviceCenterId
      } = this.data.storeInfo
      let cartListArr = [{
        // cart_id: item.cartId,
        sku_id: event.detail.skuId,
        spu_id: event.detail.spuId,
        amount: event.detail.skuAmount,
      }]
      wx.navigateTo({
        url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}&type=3`
      })
    }

  },

  // 选择商品规格 - 关闭商品规格弹出层
  onCloseSkuPopup() {
    this.setData({
      isShowGoodsSkuPopup: false
    })
  },

  // 清空购物车
  onClearCartList() {
    storeModel.deleteCartGoods({
      store_id: this.data.storeId
    }).then((res) => {
      // this.setData({
      //   isShowCartAlert: false,
      //   isClearingBtnClick: false
      // })
      this.httpGetCartList()
    })
  },

  // 修改购物车商品数量
  onChangeStepper(event) {
    const {
      goods
    } = event.detail
    storeModel.addGoodsNumToStoreCart({
      goods: [goods],
      storeId: this.data.storeId,
      userId: this.data.userInfo.uid
    }).then((res) => {
      this.httpGetCartList()
    })
  },

  // 添加到购物车
  httpAddCartGoods(param) {
    return storeModel.addGoodsToStoreCart(param).then((res) => {
      //utils.msg('已加入购物车！')
      this.httpGetCartList()
    }).catch((err) => {
      if (err.code === 2007) {
        utils.msg('请登录后操作！')
      }
    })
  },

  // 获取购物车列表
  httpGetCartList() {
    return storeModel.getStoreCartList({
      storeId: this.data.storeId,
      userId: this.data.userInfo.uid
    }).then((res) => {
      if (!res.skuList || (res.skuList && res.skuList.length === 0)) {
        this.setData({
          cartDiscountsInfo: cartDiscountsMap(res),
          cartList: res.skuList ? cartListMap(res.skuList) : [],
          needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : [],
          isShowCartAlert: false,
          isClearingBtnClick: false
        })
      } else {
        this.setData({
          cartDiscountsInfo: cartDiscountsMap(res),
          cartList: res.skuList ? cartListMap(res.skuList) : [],
          needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : []
        })
      }
    })
  },

  // 获取商品分类
  httpGetGoodsCategory() {
    return storeModel.getGoodsCategory({
      store_id: this.data.storeId,
      parent_id: 0,
    }).then((res) => {
      const {
        tabList,
        toPageCategroyId
      } = this.data
      tabList['categroy'].categroyList = res.categroy_list.map(item => {
        return {
          id: item.id,
          name: item.categroy_name,
          img: item.categroy_image_url,
          type: item.layout_type // 1:普通类目布局，2:秒杀商品布局
        }
      })
      this.setData({
        tabList: tabList,
        goodsCategroyId: res.categroy_list[0] && res.categroy_list[0].id,
        isSeckillCategroy: res.categroy_list[0] && res.categroy_list[0].layout_type === 2
      })
      if (toPageCategroyId && toPageCategroyId > 0) {
        let list = tabList['categroy'].categroyList
        let type = 0
        let index = 0
        for (let i = 0; i < list.length; i++) {
          if (list[i]['id'] == toPageCategroyId) {
            type = list[i]['type']
            index = i
          }
        }
        this.onSelectSidebarItem(toPageCategroyId, type, index)
      } else {
        // this.httpGetGoodsList()
        this.httpGetTwoGoodsCategory()
      }
    })
  },

  httpGetTwoGoodsCategory() {
    let {
      goodsCategroyId
    } = this.data;
    return storeModel.getGoodsCategory({
      store_id: this.data.storeId,
      parent_id: goodsCategroyId,
    }).then((res) => {
      let twoList = res.categroy_list
      if (twoList.length > 0) {
        this.httpGetGoodsList()
      } else {
        this.httpGetGoodsList()
      }
      this.setData({
        twoTabList: twoList,
        curTwoIndex: -1
      })
    })
  },
  clickTwoTab({
    currentTarget
  }) {
    let {
      id,
      index
    } = currentTarget.dataset
    if (index == this.data.curTwoIndex) {
      index = -1
    }
    this.setData({
      curTwoCategroyId: id,
      curTwoIndex: index
    })
    if (index > -1) {
      this.httpGetGoodsList(id)
    }else{
      this.httpGetGoodsList()
    }
  },
  // 获取商品列表
  httpGetGoodsList(id) {
    this.setData({
      isLoading: true
    })
    const {
      storeId,
      goodsCategroyId,
      tabList
    } = this.data
    return storeModel.getGoodsList({
      store_id: storeId,
      goods_categroy_id: id || goodsCategroyId,
      page: tabList['categroy'].page,
      page_size: tabList['categroy'].pageSize
    }).then((res) => {
      let resMap = storeGoodsListMap(res.goods_list)
      let goodsListArr = tabList['categroy'].page === 1 ? resMap : tabList['categroy'].list.concat(resMap)
      tabList['categroy'].list = goodsListArr
      tabList['categroy'].totalNum = res.total_count
      let setDataObj = {
        tabList: tabList,
        isLoading: false,
        isNotMore: goodsListArr.length >= res.total_count
      }
      this.setData(setDataObj)
      if (this.data.isFirstGoodsRequest) {
        let firstGoodsInfo = goodsListArr[0]
        storeModel.compoundGoodsPoster({
          goods_id: firstGoodsInfo.goodsId
        }).then((res) => {
          this.setData({
            isFirstGoodsRequest: false
          })
          this.shareOption['title'] = firstGoodsInfo.goodsName;
          this.shareOption['path'] = `pages/store/index/store?id=${storeId}`;
          this.shareOption['imageUrl'] = res;
        }).catch(() => {
          this.setData({
            isFirstGoodsRequest: false
          })
          this.shareOption['title'] = storeInfo.storeName;
          this.shareOption['path'] = `pages/store/index/store?id=${storeId}`;
          this.shareOption['imageUrl'] = storeInfo.storeImg;
        })
      }

    }).catch((err) => {
      this.setData({
        isLoading: false
      })
    })
  },

  // 获取店铺信息
  httpGetStoreInfo(id) {
    // const {
    //   longitude,
    //   latitude
    // } = this.data
    return storeModel.getStoreInfo({
      // "lng": longitude || 0, // 经度
      // "lat": latitude || 0, // 纬度
      "store_id": id
    }).then((res) => {
      const {
        store_info
      } = res
      wx.setNavigationBarTitle({
        title: store_info.store_info
      });
      let info = storeInfoMap(store_info)
      this.setData({
        isStoreOpen: info.isOpening,
        storeInfo: info
      })
    })
  },

  // 获取地理位置信息
  httpWxGetLocation() {
    let self = this;
    return new Promise((resolve, reject) => {
      let flag = false;
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          self.setData({
            longitude: res.longitude, // 经度
            latitude: res.latitude // 维度
          });
          resolve(res);
          flag = true;
        },
        fail: function (err) {
          reject(err);
          flag = true;
        }
      });
      setTimeout(function () {
        if (flag === false) {
          resolve(res);
        }
      }, 4000);
    })
  },

  // 获取店铺评价
  httpGetStoreEvaluation() {
    const {
      storeId,
      tabList,
      evaluationType,
      evaluationTag
    } = this.data
    return evaluationModel.getStoreEvaluation({
      storeId: storeId,
      hasImage: evaluationType * 1, // 评论类型：0:全部，1:有图
      type: evaluationTag, // 评论标签：1:全部，2:好评, 3:差评,其他的根据返回的storeScores中有的类型传type值。默认1
      pageNo: tabList['evaluation'].page,
      pageSize: tabList['evaluation'].pageSize
    }).then(res => {
      let evaluationListMap = res.comments.map(item => {
        return {
          avatar: item.avatar,
          nickname: item.name,
          rate: item.score,
          isMe: item.isMe === 1 ? true : false, // 0: 不是自己， 1: 自己
          createTime: formatTimeDate(new Date(item.createTime * 1000), 'yyyy-MM-dd'),
          text: item.comment,
          imgs: item.pictures
        }
      })
      let evaluationTagListMap = res.storeScores.map(item => {
        return {
          name: item.name,
          count: item.count,
          tagType: item.type
        }
      })
      tabList['evaluation'].list = tabList['evaluation'].page === 1 ? evaluationListMap : tabList['evaluation'].list.concat(evaluationListMap)
      tabList['evaluation'].totalNum = res.totalCount
      tabList['evaluation'].tagList = evaluationTagListMap
      tabList['evaluation'].rateInfo = {
        deliverRate: res.deliverScore, // 配送评分
        storeRate: res.storeScore, // 店铺评分
        packageRate: res.packageScore, // 包装评分
        qualityRate: res.tasteScore // 品质评分
      }
      this.setData({
        tabList: tabList
      })
    })
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: async function () {
    const {
      tabActive,
      tabList
    } = this.data
    switch (tabActive) {
      case 'categroy':
        tabList['categroy'].page = 1
        this.setData({
          tabList: tabList
        })
        await this.httpGetGoodsList()
        this.scrollGoodsListToTop()
        break;
      case 'details':
        await this.httpGetStoreInfo(this.data.storeId)
        break
      case 'evaluation':
        tabList['evaluation'].page = 1
        this.setData({
          tabList: tabList,
          evaluationScrollViewTop: 0
        })
        await this.httpGetStoreEvaluation()
        break
      default:
        break
    }
    wx.stopPullDownRefresh();
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function () {},

  // 生命周期函数--监听页面显示
  onShow: function () {
    this.setData({
      userInfo: app.globalData.userInfo
    })
    if (this.data.userInfo && this.data.userInfo.uid) {
      this.httpGetCartList() // 请求店铺购物车
    }
  },

  onReady: function () {

  },

  onLoad: function () {

  },
});